<template>
  <div class="alert-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>预警中心</span>
          <div class="header-actions">
            <el-select v-model="queryParams.warningLevel" placeholder="预警等级" style="width: 120px; margin-right: 10px;"
              clearable @change="handleSearch">
              <el-option label="全部" value="" />
              <el-option label="高" :value="3" />
              <el-option label="中" :value="2" />
              <el-option label="低" :value="1" />
            </el-select>
            <el-select v-model="queryParams.status" placeholder="预警状态" style="width: 120px; margin-right: 10px;"
              clearable @change="handleSearch">
              <el-option label="全部" value="" />
              <el-option label="未读" :value="0" />
              <el-option label="已读" :value="1" />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleMarkAllRead" type="success">全部标记为已读</el-button>
          </div>
        </div>
      </template>

      <el-table :data="tableData" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="violationType" label="违法类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getViolationTypeTag(row.violationType)">
              {{ getViolationTypeName(row.violationType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warningLevel" label="预警等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getWarningLevelType(row.warningLevel)">
              {{ getWarningLevelName(row.warningLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="地点" min-width="200" show-overflow-tooltip />
        <el-table-column prop="carId" label="车牌号" width="120">
          <template #default="{ row }">
            {{ row.carId || '无法识别' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 0 ? 'danger' : 'success'">
              {{ row.status === 0 ? '未读' : '已读' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看详情</el-button>
            <el-button size="small" type="primary" @click="handleMarkRead(row)" v-if="row.status === 0">
              标记已读
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination v-model:current-page="queryParams.page" v-model:page-size="queryParams.pageSize" :total="total"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <el-dialog v-model="detailVisible" title="预警详情" width="50%">
      <div class="alert-detail" v-if="currentAlert">
        <div class="alert-meta">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="违法类型">
              <el-tag :type="getViolationTypeTag(currentAlert.violationType)">
                {{ getViolationTypeName(currentAlert.violationType) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="预警等级">
              <el-tag :type="getWarningLevelType(currentAlert.warningLevel)">
                {{ getWarningLevelName(currentAlert.warningLevel) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="地点">{{ currentAlert.location }}</el-descriptions-item>
            <el-descriptions-item label="车牌号">{{ currentAlert.carId || '无法识别' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ formatDateTime(currentAlert.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="currentAlert.status === 0 ? 'danger' : 'success'">
                {{ currentAlert.status === 0 ? '未读' : '已读' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <div class="alert-images" v-if="currentAlert.imagePath">
          <h4>违法图片：</h4>
          <el-image :src="currentAlert.imagePath" fit="cover" class="alert-image" :preview-src-list="[currentAlert.imagePath]" />
        </div>
        <div class="alert-images" v-if="currentAlert.videoPath">
          <h4>违法视频：</h4>
          <video controls class="alert-video" v-if="currentAlert.videoPath">
            <source :src="currentAlert.videoPath" type="video/mp4">
            您的浏览器不支持视频播放
          </video>
        </div>
      </div>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button type="primary" @click="handleMarkRead(currentAlert)" v-if="currentAlert?.status === 0">
          标记已读
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { formatDateTime } from '@/utils/date'
import { ElMessage } from 'element-plus'
import { getAlerts, updateAlertStatus } from '@/api/alert'

const loading = ref(false)
const tableData = ref([])
const queryParams = ref({
  page: 1,
  pageSize: 10,
  warningLevel: '',
  status: '',
  location: '',
  beginTime: null,
  endTime: null
})
const total = ref(0)
const detailVisible = ref(false)
const currentAlert = ref(null)

// 获取预警数据
const fetchData = async () => {
  loading.value = true
  try {
    const response = await getAlerts(queryParams.value)
    if (response.code) {
      tableData.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error('获取预警数据失败：' + response.msg)
    }
  } catch (error) {
    console.error('获取预警数据失败:', error)
    ElMessage.error('获取预警数据失败：' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  queryParams.value.page = 1
  fetchData()
}

const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  fetchData()
}

const handleCurrentChange = (val) => {
  queryParams.value.page = val
  fetchData()
}

const handleView = (row) => {
  currentAlert.value = row
  detailVisible.value = true
}

const handleMarkRead = async (row) => {
  try {
    // 格式化日期为后端期望的格式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    
    // 修改为yyyy-MM-dd HH:mm格式，去掉秒
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
    
    const data = {
      id: row.id,
      status: 1,  // 标记为已读
      updateTime: formattedDate
    }
    
    await updateAlertStatus(data)
    ElMessage.success('已标记为已读')
    if (detailVisible.value) {
      detailVisible.value = false
    }
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败：' + (error.message || '未知错误'))
  }
}

const handleMarkAllRead = async () => {
  try {
    // 批量更新所有未读预警
    const unreadAlerts = tableData.value.filter(alert => alert.status === 0)
    if (unreadAlerts.length === 0) {
      ElMessage.info('没有未读预警')
      return
    }
    
    // 格式化日期为后端期望的格式
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    
    // 修改为yyyy-MM-dd HH:mm格式，去掉秒
    const formattedDate = `${year}-${month}-${day} ${hours}:${minutes}`;
    
    for (const alert of unreadAlerts) {
      await updateAlertStatus({
        id: alert.id,
        status: 1,
        updateTime: formattedDate
      })
    }
    ElMessage.success('已全部标记为已读')
    fetchData()
  } catch (error) {
    ElMessage.error('操作失败：' + (error.message || '未知错误'))
  }
}

// 获取违法类型名称
const getViolationTypeName = (type) => {
  const typeMap = {
    1: '超速',
    2: '未按导向行驶', 
    3: '车辆压线',
    4: '车辆闯红灯',
    5: '行人闯红灯'
  }
  return typeMap[type] || '未知'
}

// 获取违法类型标签样式
const getViolationTypeTag = (type) => {
  const tagMap = {
    1: 'warning',
    2: 'info',
    3: 'warning',
    4: 'danger',
    5: 'danger'
  }
  return tagMap[type] || 'info'
}

// 获取预警等级名称
const getWarningLevelName = (level) => {
  const levelMap = {
    1: '低',
    2: '中',
    3: '高'
  }
  return levelMap[level] || '未知'
}

// 获取预警等级标签样式
const getWarningLevelType = (level) => {
  const typeMap = {
    1: 'info',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[level] || 'info'
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.alert-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.alert-detail {
  padding: 20px;
}

.alert-meta {
  margin-bottom: 20px;
}

.alert-images {
  margin-top: 20px;
}

.alert-image {
  width: 300px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.3s;
}

.alert-video {
  width: 100%;
  max-width: 600px;
  border-radius: 4px;
}

.alert-image:hover {
  transform: scale(1.02);
}
</style>